using B.S.XZYData.Api.Read.Application.Command.Team;
using B.S.XZYData.Domain.XZY;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure;
using MediatR;

namespace B.S.XZYData.Api.Read.Application.Handler.Team
{
    /// <summary>
    /// 获取班组详情处理器
    /// </summary>
    public class GetTeamDetailHandler : IRequestHandler<GetTeamDetailCommand, ApiResult<TeamDetailDto>>
    {
        private readonly MyDbContext _dbContext;

        public GetTeamDetailHandler(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<ApiResult<TeamDetailDto>> Handle(GetTeamDetailCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取班组信息
                var team = await _dbContext.Team.InSingleAsync(request.TeamId);
                if (team == null || team.IsDeleted)
                {
                    return new ApiResult<TeamDetailDto>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "班组不存在",
                        Data = null
                    };
                }

                // 获取班组成员
                var teamMembers = await _dbContext.TeamMember
                    .Where(x => x.TeamId == request.TeamId && !x.IsDeleted)
                    .ToListAsync();

                // 获取创建人和修改人信息
                var creator = await _dbContext.AccountModel.InSingleAsync(team.CreatorId);
                var modifier = team.ModifierId.HasValue ? await _dbContext.AccountModel.InSingleAsync(team.ModifierId.Value) : null;

                // 获取班组成员的创建人和修改人信息
                var memberCreatorIds = teamMembers.Select(m => m.CreatorId).Distinct().ToList();
                var memberModifierIds = teamMembers.Where(m => m.ModifierId.HasValue).Select(m => m.ModifierId.Value).Distinct().ToList();
                var allUserIds = memberCreatorIds.Concat(memberModifierIds).Distinct().ToList();
                
                var users = new Dictionary<int, string>();
                foreach (var userId in allUserIds)
                {
                    var user = await _dbContext.AccountModel.InSingleAsync(userId);
                    if (user != null)
                    {
                        users[userId] = user.RealName;
                    }
                }

                // 构建班组详情DTO
                var teamDetailDto = new TeamDetailDto
                {
                    Id = team.Id,
                    TeamName = team.TeamName,
                    TeamCode = team.TeamCode,
                    TeamType = (int)team.TeamType,
                    Remark = team.Remark,
                    CreateTime = team.CreateTime,
                    Creator = creator?.RealName ?? "未知",
                    ModifyTime = team.ModifyTime,
                    Modifier = modifier?.RealName ?? "未知",
                    TeamMembers = teamMembers.Select(member => new TeamMemberDto
                    {
                        Id = member.Id,
                        AccountId = member.Id, // 使用成员ID作为AccountId，或者根据实际业务逻辑调整
                        MemberName = member.MemberName,
                        MemberRealName = member.MemberRealName,
                        Phone = member.Phone,
                        CreateTime = member.CreateTime,
                        Creator = users.ContainsKey(member.CreatorId) ? users[member.CreatorId] : "未知",
                        ModifyTime = member.ModifyTime,
                        Modifier = member.ModifierId.HasValue && users.ContainsKey(member.ModifierId.Value) ? users[member.ModifierId.Value] : "未知"
                    }).ToList()
                };

                return new ApiResult<TeamDetailDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取班组详情成功",
                    Data = teamDetailDto
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<TeamDetailDto>
                {
                    Code = ApiEnum.Error,
                    Msg = $"获取班组详情失败: {ex.Message}",
                    Data = null
                };
            }
        }
    }
}
